from api import ApiServer
from db_model import Record
from db_model import Poll
from google.appengine.ext import db
import urllib

import json
class CreateServer(ApiServer):
  def get(self):
    self.post()

  def post(self):
    create_type = self.request.get('create_type')
    if create_type == 'vote':
      record = Record()
      record.pollee_id = self.request.get('opensocial_viewer_id')
      record.poll_id = db.Key(self.request.get('poll_id'))
      record.selected_options = self.request.get('options')
      poll_voted = self._getPolledRecords(record.pollee_id, record.poll_id)
      if not poll_voted or poll_voted.count() == 0:
        record.put()
        self.response.out.write('<br>you just voted this poll')
      else:
        self.response.out.write('<br>you have voted this poll')

    elif create_type == 'poll':
      poll = Poll()
      poll.creator_id = self.request.get('opensocial_viewer_id')
      poll.description= self.request.get('description')

      if self.request.get('start_time'):
        poll.start_time = self.request.get('start_time')

      if self.request.get('end_time'):
        poll.end_time = self.request.get('end_time')

      if self.request.get('type'):
        poll.type = self.request.get('type')

      if self.request.get('options'):
        poll.options = self.request.get('options').split(',')

      if self.request.get('max_select'):
        poll.max_select = int(self.request.get('max_select'))

      if self.request.get('access'):
        poll.access = self.request.get('access')
      else:
        poll.access = 'friend'

      if not (poll.creator_id and poll.options and poll.description):
        return

      poll.put()
      self.response.out.write('<br>you have created a poll')
      return

    self.response.out.write('<br>you do not create a poll')


  def _getPolledRecords(self, pollee_id, poll_id=None):
    results = []
    if not poll_id:
      results = Record.gql('WHERE pollee_id=:pollee_id', pollee_id=poll_id)
    else:
      results = Record.gql('WHERE pollee_id=:pollee_id AND poll_id=:poll_id', pollee_id=pollee_id, poll_id=poll_id)
    return results
